{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "4f703306",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "3\n",
      "2\n",
      "4\n"
     ]
    }
   ],
   "source": [
    "import gevent\n",
    "\n",
    "def test(time):\n",
    "    print(1)\n",
    "    gevent.sleep(time)\n",
    "    print(2)\n",
    "\n",
    "def test2(time):\n",
    "    print(3)\n",
    "    gevent.sleep(time)\n",
    "    print(4)\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    gevent.joinall([\n",
    "        gevent.spawn(test, 2),\n",
    "        gevent.spawn(test2, 3)\n",
    "    ]) "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "id": "dda84185",
   "metadata": {},
   "outputs": [
    {
     "ename": "RuntimeError",
     "evalue": "asyncio.run() cannot be called from a running event loop",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mRuntimeError\u001b[0m                              Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-45-d4ff7419c35c>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[1;32m     14\u001b[0m     \u001b[0;32mawait\u001b[0m \u001b[0masyncio\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mgather\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0mtasks\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     15\u001b[0m \u001b[0mstart\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mtime\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mtime\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 16\u001b[0;31m \u001b[0masyncio\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mrun\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mmain\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m     17\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mtime\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mtime\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;34m-\u001b[0m \u001b[0mstart\u001b[0m \u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     18\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;32m~/anaconda3/lib/python3.8/asyncio/runners.py\u001b[0m in \u001b[0;36mrun\u001b[0;34m(main, debug)\u001b[0m\n\u001b[1;32m     31\u001b[0m     \"\"\"\n\u001b[1;32m     32\u001b[0m     \u001b[0;32mif\u001b[0m \u001b[0mevents\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_get_running_loop\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;32mis\u001b[0m \u001b[0;32mnot\u001b[0m \u001b[0;32mNone\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 33\u001b[0;31m         raise RuntimeError(\n\u001b[0m\u001b[1;32m     34\u001b[0m             \"asyncio.run() cannot be called from a running event loop\")\n\u001b[1;32m     35\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;31mRuntimeError\u001b[0m: asyncio.run() cannot be called from a running event loop"
     ]
    }
   ],
   "source": [
    "import aiohttp\n",
    "import asyncio\n",
    "import time\n",
    "\n",
    "async def get(url):\n",
    "    async with aiohttp.ClientSession() as session:\n",
    "        async with session.get(url) as response:\n",
    "            return response\n",
    "async def request():\n",
    "    url = \"http://www.baidu.com\"\n",
    "    await get(url)\n",
    "async def main():\n",
    "    tasks = [request()] * 100\n",
    "    await asyncio.gather(*tasks)\n",
    "start = time.time() \n",
    "asyncio.run(main())\n",
    "print(time.time() - start )\n",
    "\n",
    "# loop = asyncio.get_event_loop()#创建事件循环池\n",
    "# loop.run_until_complete(asyncio.wait(tasks)) "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "450899e6",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "start func\n",
      "start func\n",
      "start func\n",
      "end func\n",
      "end func\n",
      "end func\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "[<Greenlet at 0x10a05cbf0: _run>,\n",
       " <Greenlet at 0x10a05cd00: _run>,\n",
       " <Greenlet at 0x10a05ce10: _run>]"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import asyncio\n",
    "from aiohttp import request\n",
    "from aiomultiprocess import Process\n",
    "\n",
    "async def put(url, params):\n",
    "    async with request(\"PUT\", url, params=params) as response:\n",
    "        #pass\n",
    "        print(response)\n",
    "\n",
    "async def main():\n",
    "    p = Process(target=put, args=(\"https://jreese.sh\", \"\"))\n",
    "    await p\n",
    "\n",
    "if __name__=='__main__':\n",
    "    asyncio.run(main())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "0dcf31f3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "start func\n",
      "start func\n",
      "start func\n",
      "end func\n",
      "end func\n",
      "end func\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "[<Greenlet at 0x109ba3040: _run>,\n",
       " <Greenlet at 0x10a1f1040: _run>,\n",
       " <Greenlet at 0x10a1f1150: _run>]"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import gevent\n",
    "def func():  #所有带有IO操作的内容都写在函数里，然后提交function\n",
    "    print('start func')\n",
    "    gevent.sleep(1)\n",
    "    print('end func')\n",
    "g1=gevent.spawn(func)\n",
    "g2=gevent.spawn(func)\n",
    "g3=gevent.spawn(func)\n",
    "# gevent.sleep(2)\n",
    "# g1.join()  #一直阻塞，直到协程g1任务执行结束\n",
    "# g2.join()\n",
    "# g3.join()\n",
    "gevent.joinall([g1,g2,g3])\t"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "f9851406",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "<ipython-input-12-ab53e90f6a62>:2: MonkeyPatchWarning: Monkey-patching ssl after ssl has already been imported may lead to errors, including RecursionError on Python 3.6. It may also silently lead to incorrect behaviour on Python 3.7. Please monkey-patch earlier. See https://github.com/gevent/gevent/issues/1016. Modules that had direct imports (NOT patched): ['aiohttp.connector (/Users/apple/anaconda3/lib/python3.8/site-packages/aiohttp/connector.py)', 'aiohttp.client (/Users/apple/anaconda3/lib/python3.8/site-packages/aiohttp/client.py)', 'aiohttp.client_reqrep (/Users/apple/anaconda3/lib/python3.8/site-packages/aiohttp/client_reqrep.py)', 'aiohttp.client_exceptions (/Users/apple/anaconda3/lib/python3.8/site-packages/aiohttp/client_exceptions.py)']. \n",
      "  monkey.patch_all()  #此两句必须写在所有导入模块的最上面，否则报错\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "start func\n",
      "start func\n",
      "start func\n",
      "end func\n",
      "end func\n",
      "end func\n"
     ]
    }
   ],
   "source": [
    "from gevent import monkey\n",
    "monkey.patch_all()  #此两句必须写在所有导入模块的最上面，否则报错\n",
    "import gevent\n",
    "import time\n",
    "def func():  #所有带有IO操作的内容都写在函数里，然后提交function\n",
    "    print('start func')\n",
    "    time.sleep(1)\n",
    "    print('end func')\n",
    "g1=gevent.spawn(func)\n",
    "g2=gevent.spawn(func)\n",
    "g3=gevent.spawn(func)\n",
    "time.sleep(2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "7e60f44a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<!DOCTYPE html>\r\n",
      "<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/bdorz/baidu.min.css><title>ç¾åº¦ä¸ä¸ï¼ä½ å°±ç¥é</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class=fm> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1> <input type=hidden name=rsv_idx value=1> <input type=hidden name=tn value=baidu><span class=\"bg s_ipt_wr\"><input id=kw name=wd class=s_ipt value maxlength=255 autocomplete=off autofocus=autofocus></span><span class=\"bg s_btn_wr\"><input type=submit id=su value=ç¾åº¦ä¸ä¸ class=\"bg s_btn\" autofocus></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>æ°é»</a> <a href=https://www.hao123.com name=tj_trhao123 class=mnav>hao123</a> <a href=http://map.baidu.com name=tj_trmap class=mnav>å°å¾</a> <a href=http://v.baidu.com name=tj_trvideo class=mnav>è§é¢</a> <a href=http://tieba.baidu.com name=tj_trtieba class=mnav>è´´å§</a> <noscript> <a href=http://www.baidu.com/bdorz/login.gif?login&amp;tpl=mn&amp;u=http%3A%2F%2Fwww.baidu.com%2f%3fbdorz_come%3d1 name=tj_login class=lb>ç»å½</a> </noscript> <script>document.write('<a href=\"http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u='+ encodeURIComponent(window.location.href+ (window.location.search === \"\" ? \"?\" : \"&\")+ \"bdorz_come=1\")+ '\" name=\"tj_login\" class=\"lb\">ç»å½</a>');\r\n",
      "                </script> <a href=//www.baidu.com/more/ name=tj_briicon class=bri style=\"display: block;\">æ´å¤äº§å</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a href=http://home.baidu.com>å",
      "³äºç¾åº¦</a> <a href=http://ir.baidu.com>About Baidu</a> </p> <p id=cp>&copy;2017&nbsp;Baidu&nbsp;<a href=http://www.baidu.com/duty/>ä½¿ç¨ç¾åº¦åå¿",
      "è¯»</a>&nbsp; <a href=http://jianyi.baidu.com/ class=cp-feedback>æè§åé¦</a>&nbsp;äº¬ICPè¯030173å·&nbsp; <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>\r\n",
      "\n",
      "0.43154001235961914\n"
     ]
    }
   ],
   "source": [
    "# from gevent import monkey\n",
    "# monkey.patch_all() \n",
    "\n",
    "import requests\n",
    "import time\n",
    "\n",
    "start = time.time()\n",
    "def get():\n",
    "    return requests.get('https://www.baidu.com/').text\n",
    "\n",
    "a = gevent.joinall([gevent.spawn(get)] * 100)\n",
    "print(a[0].value)\n",
    "print(time.time() - start )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0ee26ed7",
   "metadata": {},
   "outputs": [],
   "source": [
    "import aiohttp\n",
    "\n",
    "async def get():\n",
    "    async with aiohttp.ClientSession as session:\n",
    "        async with session"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f1e27c4f",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
